#!/usr/bin/env python3
# -*- coding: utf-8 -*-
# ----------------------------------------------------------
# -- This"s python application views
# -- 
# ****************************
# Author: lmay.Zhou
# Blog: www.lmaye.com
# Date: 2018年2月13日 09:45:13
# ----------------------------------------------------------
import logging
from logging.handlers import SMTPHandler
from flask import Flask
from flask_babel import Babel, lazy_gettext
from flask_mail import Mail
from flask_sqlalchemy import SQLAlchemy
from core.constant.sys_enum import SysEnum
from flask_login import LoginManager
from flask_openid import OpenID
from core.logger.log import logger
from core.utils.momentjs import momentjs
from core.utils.pub_utils import CustomJSONEncoder
# 日志
LOG = logger()
from core.utils import read_config

# static_url_path   静态资源
# static_folder     静态资源路径
# template_folder   HTML路径
app = Flask(__name__, static_url_path="/static", static_folder="../resources/static",
            template_folder="../resources/templates")
application = read_config.read_yml(SysEnum.APPLICATION_PATH.value)
flask_wtf = application["flask"]["wtf"]
LOG.info("flask_wtf: {}".format(flask_wtf))
app.config.from_mapping(flask_wtf)
# Use Databases
databases = application["server"]["databases"]
db_yml = read_config.read_yml(SysEnum.DB_PATH.value)
databases_obj = db_yml[databases]
if databases == "mysql":
    app.config["SQLALCHEMY_DATABASE_URI"] = "mysql://" + databases_obj["user"] + ":" + databases_obj["password"] + "@" \
                                            + databases_obj["host"] + ":" + str(databases_obj["port"]) + "/" \
                                            + databases_obj["database"] + "?charset=" + databases_obj["charset"]
else:
    app.config["SQLALCHEMY_DATABASE_URI"] = "sqlite:///" + SysEnum.RESOURCES_PATH.value + SysEnum.SEPARATOR.value \
                                            + databases_obj["SQLALCHEMY_DATABASE_URI"]
app.config["SQLALCHEMY_TRACK_MODIFICATIONS"] = databases_obj["SQLALCHEMY_TRACK_MODIFICATIONS"]

# 全文搜索
app.config["WHOOSH_BASE"] = SysEnum.WHOOSH_BASE.value
app.config["MAX_SEARCH_RESULTS"] = SysEnum.MAX_SEARCH_RESULTS.value
db = SQLAlchemy(app)

# Moment JS
app.jinja_env.globals["momentjs"] = momentjs

lm = LoginManager()
lm.init_app(app)
lm.login_view = "/user/login"
lm.login_message = lazy_gettext('Please log in to access this page.')
lm.login_message_category = "info"
oid = OpenID(app, SysEnum.TEMP_PATH.value)

# Email Server
email = application["email"]
app.config.from_mapping(email)
mail = Mail(app)

# 国际化和本地化
languages = application["server"]["LANGUAGES"]
# app.config["BABEL_DEFAULT_LOCALE"] = "zh_cn"
# app.config["BABEL_DEFAULT_TIMEZONE"] = "Asia/Shanghai"
app.config["BABEL_TRANSLATION_DIRECTORIES"] = "../resources/translations"
babel = Babel(app)
app.json_encoder = CustomJSONEncoder

# Models 导入
from core.models import user_model, post_model

# Views 导入
from core.views import user_views, home_views, error_views, editor_views

if not app.debug:
    if email["MAIL_SERVER"]:
        auth = None
        if email["MAIL_USERNAME"] or email["MAIL_PASSWORD"]:
            auth = (email["MAIL_USERNAME"], email["MAIL_PASSWORD"])
        secure = None
        if email["MAIL_USE_TLS"]:
            secure = ()
        mail_handler = SMTPHandler(mailhost=(email["MAIL_SERVER"], email["MAIL_PORT"]),
                                   fromaddr="no-reply@" + email["MAIL_SERVER"],
                                   toaddrs=email["ADMINS"], subject="Microblog Failure",
                                   credentials=auth, secure=secure)
        mail_handler.setLevel(logging.ERROR)
        app.logger.addHandler(mail_handler)
